package com.example.fill;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

public class RefreshLayout extends ViewGroup {

    public RefreshLayout(Context context) {
        super(context);
    }

    public RefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public RefreshLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    View title;

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int h = t;
        for (int i = 0; i < getChildCount(); i++) {
            View childAt = getChildAt(i);
            if (i == 0) {
                title = childAt;
                childAt.layout(0, -childAt.getLayoutParams().height, r, t);
            } else {
                childAt.layout(0, h, r, h + childAt.getLayoutParams().height);
                h += childAt.getMeasuredHeight();
            }
        }
    }

    float downX = 0;
    float downY = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        getParent().requestDisallowInterceptTouchEvent(false);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                Log.i("TAG", "onTouchEvent: ");
                return true;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(event.getX() - downX) > Math.abs(event.getY() - downY) &&
                        downY > event.getY())
                    return super.onTouchEvent(event);
                float pushY = downY - event.getY();
                if (pushY > title.getHeight()) {
                    pushY = title.getHeight();
                }
                scrollTo(0, (int) pushY);
                Log.i("TAG", "onTouchEvent: ");
                return true;
            case MotionEvent.ACTION_UP:
                downX = 0;
                downY = 0;
                performClick();
                Log.i("TAG", "onTouchEvent: ");
                invalidate();
                requestLayout();
                return true;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }
}
